package com.example.validation;

import com.example.common.CommonError;
import com.example.common.CommonRes;
import com.example.common.Constants;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 * 校验执行器
 *
 * @author: jimmy
 * @date: 2024年01月13日 11:21
 */
@Configuration
public class DtoValidator {
    /**
     * 使用在com.example.config.WebMvcConfig中配置的validator
     */
    @Qualifier("localValidator")
    @Autowired
    private Validator validator;

    /**
     * 执行校验,如果返回""字符串，则校验成功，否则不成功
     *
     * @param object
     * @return
     */
    public CommonRes validate(Object object) {
        BindException bindException = new BindException(object, ""); //传入任意一个字符串类型的属性即可
        validator.validate(object, bindException);
        List<ObjectError> allErrors = bindException.getAllErrors();
        List<String> errList = new ArrayList<>();
        for (ObjectError allError : allErrors) {
            errList.add(allError.getDefaultMessage());
        }
        if (errList.size() > 0) {
            CommonError commonError = new CommonError(Constants.CODE_10005, errList);
            return CommonRes.createError(commonError);
        }
        return null;
    }

}
